
define build_subdir
all: $$(COMPILE_PRE)
	@for i in $(1); do \
	 if [ -d $$$$i ];then \
	  $(MAKE) -C $$$$i || exit $?; \
	 fi \
	done
	$$(COMPILE_EXTEND)

install: $$(INSTALL_PRE)
	@for i in $(1); do \
	 if [ -d $$$$i ];then \
	  $(MAKE) -C $$$$i install || exit $?; \
	 fi \
	done
	$$(INSTALL_POST)
	
clean: $$(CLEAN_PRE)
	@for i in $(1); do \
	 if [ -d $$$$i ];then \
	  $(MAKE) -C $$$$i clean || exit $?; \
	 fi \
	done
	$$(CLEAN_POST)

.PHONY: all install clean
endef

define build_app
SRCS ?= $(wildcard *.c)
SRC_DIR := $$(shell pwd)
OBJ_DIR := $$(APP_OBJ)/$$(notdir $$(SRC_DIR))
BASE_SRCS := $$(wildcard $$(APP_TOPDIR)/common/*.c)
BASE_SRCS += $$(wildcard $$(APP_TOPDIR)/ssiot/*.c)
BASE_SRCS += $$(wildcard $$(APP_TOPDIR)/ssiot/MQTTPacket/*.c)
SRC_OBJS := $$(addprefix $$(OBJ_DIR)/,$$(subst .c,.o,$$(SRCS) $$(BASE_SRCS)))
SRC_DEPS := $$(subst .o,.d, $$(SRC_OBJS))
DEST_APP := $$(OBJ_DIR)/$$(APP_NAME)

ifneq ($$(APP_AUTO_RUN),)
 APP_CFLAGS += -DAPP_AUTO_RUN
endif


all: $$(DEST_APP)

$$(DEST_APP): $$(SRC_OBJS) $$(STATIC_APP_DEP)
	$$(CC) -o $$@ $$^ $$(APP_LDFLAGS)
	$$(COMPILE_EXTEND)

$$(OBJ_DIR)/%.o:%.c
	@mkdir -p $$(dir $$@)
	$$(CC) -c $$(APP_CFLAGS) $$< -o $$@

clean:
	rm -rf $$(OBJ_DIR)
	$$(CLEAN_EXTEND)

install:
ifneq ($(1),)
	install -d $(1)
	install -m 755 $$(DEST_APP) $(1)
	$$(STRIP) $(1)/$$(APP_NAME)
endif
	$$(INSTALL_EXTEND)

$$(OBJ_DIR)/%.d:%.c
	@mkdir -p $$(dir $$@)
	@set -e; rm -f $$@; \
	export D_FILE="$$@"; \
	export B_NAME=`echo $$$$D_FILE | sed 's/\.d//g'`; \
	$(CC) -MM $(APP_CFLAGS) $$< > $$@.$$$$; \
	sed 's@\(.*\)\.o@'"$$$$B_NAME\.o $$$$B_NAME\.d"'@g' < $$@.$$$$ > $$@; \
	rm -f $$@.$$$$

-include $$(SRC_DEPS)

.PHONY: install all clean
endef

